<?php
    include 'sqlconnect.php';
    @session_start();
    $username=$_SESSION['username'];
    echo"<ul class='list-group'><li  class='list-group-item active' data-id='q'>Your Tasks</li>";
    $sql="SELECT task.taskID,taskName FROM task,task_hierarchy,allocated_task 
    WHERE task.taskID=allocated_task.taskID and username='$username' and task.taskID not in (SELECT subTaskID FROM workload.task_hierarchy) group by task.taskID";//找到没有母任务的任务
    $result=mysqli_query($conn,$sql);
    while($row=mysqli_fetch_array($result)){
        $taskID=$row['taskID'];
        $t=mysqli_query($conn,'SELECT count(1) AS num FROM task_hierarchy WHERE taskID='.$row['taskID']);
        while($row1=mysqli_fetch_array($t)){
            $num=$row1['num'];
        }
        $pID="l_".$taskID;
        echo"<li  class='list-group-item task task-item' data-id='$taskID'>".$row['taskName'];
        if($num>0){
            $num=allsubnum($taskID);
            echo"<span class='badge '>$num</span>";
        }
        echo"</li>";
        $str="";
        isSublist($taskID,$num,$str);
    }
    echo"</ul>";
    function isSublist($ID,$n,$str){
        include 'sqlconnect.php';
        if($n>0){
            $taskID="";
            $num="";
            $sql="SELECT task_hierarchy.subtaskID,taskName FROM task_hierarchy,task 
            WHERE task.taskID=task_hierarchy.subTaskID and task_hierarchy.taskID=$ID";
            $result=mysqli_query($conn,$sql);
            echo"<ul class='$ID' style='display:none;'>";
            while($row=mysqli_fetch_array($result)){
                $taskID=$row['subtaskID'];
                $t=mysqli_query($conn,'SELECT count(1) AS num FROM task_hierarchy WHERE taskID='.$taskID);
                while($row1=mysqli_fetch_array($t)){
                    $num=$row1['num'];
                }
                $pID="l_".$taskID;
                echo"<li  class='list-group-item $ID' data-id='$taskID' style='display:none;'>".$row['taskName'];
                if($num>0){
                    $num=allsubnum($taskID);
                    echo"<span class='badge'>$num</span>";
                }
                echo"</li>";
                isSublist($taskID,$num,$str);
            }
            echo"</ul>";
        }else{
            return;
        }
    }
    function allsubnum($taskID){
        include 'sqlconnect.php';
        $sql="SELECT count(1) AS num FROM task_hierarchy WHERE taskID='$taskID'";
        $result=mysqli_query($conn,$sql);
        while($row=mysqli_fetch_array($result)){
            $n=$row['num'];
        }
        if($n>0){
            $sql="SELECT subtaskID FROM task_hierarchy WHERE taskID='$taskID'";
            $result=mysqli_query($conn,$sql);
            while($row=mysqli_fetch_array($result)){
                return $n+allsubnum($row['subtaskID']);
            }
        }
        else{
            return 0;
        }       
    }
?>